/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ftpcombiner.properties;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ftpcombiner.ApplicationController;
import ftpcombiner.filesystem.FileSystem;
import ftpcombiner.gui.GUIResources;
import ftpcombiner.server.ServerConnection;
import java.io.*;
import java.util.ArrayList;

/**
 *
 * @author Ben
 */
public class ApplicationProperties {

    private ServerArrayList servers;
    private File propertiesFile;
    Gson gson = new Gson();

    public ServerArrayList getServerProperties() {
        return servers;
    }

    public ApplicationProperties(File propertiesFile) {
        this.propertiesFile = propertiesFile;
        load();
    }

    public void updateProperties() {
        for (int i = 0; i < FileSystem.getInstance().getServerCount(); i++) {
            servers.addOrSet(i, new ServerProperties(FileSystem.getInstance().getServer(i)));
        }
    }

    public class ServerArrayList extends ArrayList<ServerProperties> {

        public ServerArrayList(int initialCapacity) {
            super(initialCapacity);
        }

        public ServerArrayList() {
            super();
        }

        private void addOrSet(int index, ServerProperties element) {
            try {
                set(index, element);
            } catch (IndexOutOfBoundsException e) {
                add(index, element);
            }
        }
    }

    private void load() {
        System.out.println("Loading preferences...");
        servers = new ServerArrayList();
        JsonReader jsonReader = null;
        try {
            //System.out.println(propertiesFile.getPath());
            System.out.println("Checking for preferences file...");
            jsonReader = new JsonReader(new FileReader(propertiesFile));
            System.out.println("File exists.");
            try {
                ApplicationController.getSplashScreen().incrementProgress();
            } catch (UnsupportedOperationException ex) {
            }
        } catch (FileNotFoundException ex) {
            System.err.println("Preferences file not found.");
            System.out.println("Creating new preferences file...");
            createDefaultPropertiesFile();
            try {
                jsonReader = new JsonReader(new FileReader(propertiesFile));
                try {
                    ApplicationController.getSplashScreen().incrementProgress();
                } catch (UnsupportedOperationException e) {
                }
            } catch (FileNotFoundException ex_bad) {
                System.err.println("Oh no, somethin' bad happin'd, program quitting - LOOK AT JAVA RESULT CODE!");
                System.exit(42);
            }
        }

        try {

            boolean go = true;
            while (go) {
                try {
                    servers.add((ServerProperties) gson.fromJson(jsonReader, ServerProperties.class));
                    //System.out.print("go ");
                } catch (JsonSyntaxException e) {
                    go = false;
                    //e.printStackTrace(System.err);
                }
                //System.out.println();
            }

            jsonReader.close();
        } catch (IOException ex) {
        }
        System.out.println("Finished loading preferences");
        try {
            ApplicationController.getSplashScreen().incrementProgress();
        } catch (UnsupportedOperationException ex) {
        }
    }

    public void save() {
        System.out.println("saving");
        updateProperties();
        JsonWriter json = null;
        try {
            json = new JsonWriter(new FileWriter(propertiesFile));
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
        for (int i = 0; i < servers.size(); i++) {
            gson.toJson(servers.get(i), ServerProperties.class, json);
        }
        try {
            json.close();
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }

    private void createDefaultPropertiesFile() {
        try {
            (new File(propertiesFile.getParent())).mkdir();
            propertiesFile.createNewFile();
            InputStream input = GUIResources.getInstance().getDefaultPropertiesStream();
            FileOutputStream output = new FileOutputStream(propertiesFile);
            while (input.available() > 0) {
                int copy = input.read();
                output.write(copy);
                //System.out.print((char)copy);
            }
            //System.out.println("\n"+propertiesFile.length());
        } catch (IOException ex) {
            System.err.println("Could not create preferences file: " + ex);
        }
    }

    public class ServerProperties {

        private String username, password, url;

        public ServerProperties(String username, String password, String url) {
            this.username = username;
            this.password = password;
            this.url = url;
        }

        public ServerProperties(ServerConnection server) {
            this.url = server.getHost();
            this.password = server.getPassword();
            this.username = server.getUsername();
        }

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }

        public String getUrl() {
            return url;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public void setUsername(String username) {
            this.username = username;
        }
    }
}